<script setup lang="ts">
import { ref } from 'vue'
import { regYuanToFen, toYuan, timeFormat } from '@/hooks/util'
import * as xyApi from '@/api/xy'
import { message } from 'ant-design-vue'

const modleRef = ref()
let spinning = ref<boolean>(false)

let showType = ref<number>(0)
const orderInfo = ref()

let title = ref<string>('订单详情')

const show = (record: any, type: number) => {
  getReasonList()
  showType.value = type
  if (type == 0) {
    title.value = '取消订单'
  } else if (type == 1) {
    title.value = '改价'
  }
  orderInfo.value = record
  modleRef.value.showModal()
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  show,
})

const formRef = ref()
interface formState {
  changeBalance: number
  cancelReason: string
}
const formState = ref<formState>({
  changeBalance: 0,
  cancelReason: '',
})
import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }
  return Promise.resolve()
}
import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  changeBalance: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  cancelReason: [{ required: true, message: '请输入取消订单的原因', trigger: 'blur' }],
}
const editPrice = async () => {
  formRef.value.validate().then(async () => {
    spinning.value = true
    let params = {
      id: orderInfo.value.id,
      price: regYuanToFen(formState.value.changeBalance, 100),
    }
    try {
      const { state, message: msg } = await xyApi.changePrice(params)
      if (state === 200) {
        modleRef.value?.cancelModal()
        emit('refresh')
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    spinning.value = false
  })
}

const getReasonList = async () => {
  try {
    const { state, data, message: msg } = await xyApi.cancelOrderReasonList()
    if (state === 200) {
      cancelReasonList.value = data.map(item => {
        return {
          label: item,
          value: item,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 取消订单的条件列表
import type { SelectProps } from 'ant-design-vue'
const cancelReasonList = ref<SelectProps['options']>([])
const selectReason = (value: string) => {
  formState.value.cancelReason = value
  // console.log('formState=', formState.value.cancelReason)
}

// 取消订单
const cancelOrder = async () => {
  formRef.value.validate().then(async () => {
    spinning.value = true
    let params = {
      id: orderInfo.value.id,
      cancelReason: formState.value.cancelReason,
    }
    try {
      const { state, message: msg } = await xyApi.orderCancel(params)
      if (state === 200) {
        modleRef.value?.cancelModal()
        emit('refresh')
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    } finally {
      spinning.value = false
    }
  })
}
</script>

<template>
  <MyModal ref="modleRef" :title="title" :width="800" :top="35">
    <template #content>
      <a-spin :spinning="spinning">
        <div>
          <div class="itemBox">
            <span class="title">订单编号：</span>
            <span class="content">{{ orderInfo?.orderNumber }}</span>

            <span class="title">退款订单号：</span>
            <span class="content">{{ orderInfo?.refundOrderId || '-' }}</span>
          </div>
          <div class="itemBox">
            <span class="title">商品标题：</span>
            <span class="content">{{ orderInfo?.productTitle }}</span>

            <span class="title">退款订单状态：</span>
            <span class="content">
              <a-tag color="red" v-if="orderInfo?.orderStatus == '0'">未知状态</a-tag>
              <a-tag color="blue" v-if="orderInfo?.orderStatus == '1'">已创建</a-tag>
              <a-tag color="blue" v-if="orderInfo?.orderStatus == '2'">已付款</a-tag>
              <a-tag color="blue" v-if="orderInfo?.orderStatus == '3'">已发货</a-tag>
              <a-tag color="blue" v-if="orderInfo?.orderStatus == '4'">交易成功</a-tag>
              <a-tag color="red" v-if="orderInfo?.orderStatus == '5'">已退款</a-tag>
              <a-tag color="blue" v-if="orderInfo?.orderStatus == '6'">交易关闭</a-tag>
            </span>
          </div>

          <div class="itemBox">
            <span class="title">商品图片：</span>
            <a-popover placement="rightTop" class="content">
              <template #content>
                <div class="popoverImg">
                  <img :src="orderInfo?.productPic" alt="" />
                </div>
              </template>
              <div class="imgBox">
                <!-- <img :src="'https://img.alicdn.com/bao/uploaded/i1/O1CN01omoNdW1pTqbpG1C3p_!!0-fleamarket.jpg'" alt="获取失败..." /> -->
                <img :src="orderInfo?.productPic" alt="获取失败..." />
              </div>
            </a-popover>
            <span class="title">退款申请时间：</span>
            <span class="content">{{ timeFormat(orderInfo?.refundCreateTime) }}</span>
          </div>

          <div class="itemBox">
            <span class="title">商品价格：</span>
            <span class="content">￥{{ toYuan(orderInfo?.productPrice) }}</span>
          </div>

          <!-- <div class="itemBox">
          <span class="title">商品状态：</span>
          <span class="content">
            <a-tag v-if="orderInfo?.refundStatus === '0'" color="red">未知状态</a-tag>
            <a-tag v-else-if="orderInfo?.productStatus === '1'" color="green">订单已创建</a-tag>
            <a-tag v-else-if="orderInfo?.productStatus === '2'" color="green">订单已付款</a-tag>
            <a-tag v-else-if="orderInfo?.productStatus === '3'" color="green">已发货</a-tag>
            <a-tag v-else-if="orderInfo?.productStatus === '4'" color="green">交易成功</a-tag>
            <a-tag v-else-if="orderInfo?.productStatus === '5'" color="red">已退款</a-tag>
            <a-tag v-else-if="orderInfo?.productStatus === '6'" color="red">交易关闭</a-tag>
          </span>
        </div> -->

          <div style="border-top: 1px solid #f0f0f0; margin: 15px 0"></div>

          <div>
            <div class="itemBox">
              <span class="title">买家昵称：</span>
              <span class="content">{{ orderInfo?.fansNickName || '-' }}</span>

              <span class="title">卖家昵称：</span>
              <span class="content">{{ orderInfo?.sellerNick || '-' }}</span>
            </div>
            <div class="itemBox">
              <span class="title">是否退货：</span>
              <span class="content">{{ orderInfo?.needReturnProduct ? '是' : '否' }}</span>

              <span class="title">卖家拒绝原因：</span>
              <span class="content">{{ orderInfo?.sellerRefuseReason || '-' }}</span>
            </div>

            <div class="itemBox">
              <span class="title">退款描述：</span>
              <span class="content">{{ orderInfo?.buyerRefundDesc || '-' }}</span>

              <span class="title">卖家拒绝退款：</span>
              <span class="content">{{ orderInfo?.sellerRefuseMsg || '-' }}</span>
            </div>

            <div class="itemBox">
              <span class="title">退款原因：</span>
              <span class="content">{{ orderInfo?.refundReason }}</span>
            </div>

            <div class="itemBox">
              <span class="title">二级原因：</span>
              <span class="content">{{ orderInfo?.refundSubReason }}</span>
            </div>
          </div>

          <div class="itemBox">
            <a-form
              ref="formRef"
              layout="inline"
              :rules="rules"
              :model="formState"
              style="margin-left: 8px"
            >
              <a-form-item v-if="showType == 1" has-feedback label="修改价格" name="changeBalance">
                <a-input-number
                  v-model:value="formState.changeBalance"
                  style="width: 70%"
                ></a-input-number>
              </a-form-item>

              <a-form-item v-if="showType == 0" has-feedback label="取消订单" name="cancelReason">
                <!-- <a-textarea
                  style="width: 450px; max-height: 60px"
                  v-model:value="formState.cancelReason"
                  placeholder="取消订单的原因"
                ></a-textarea> -->
                <a-select
                  v-model:value="formState.cancelReason"
                  placeholder="取消原因"
                  style="width: 450px"
                  @change="selectReason"
                >
                  <a-select-option
                    v-for="(item, index) in cancelReasonList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </div>

          <div style="text-align: right; margin-right: 10px">
            <a-button style="margin-right: 10px" @click="modleRef.cancelModal()">取消</a-button>
            <a-button v-if="showType == 1" type="primary" @click="editPrice">改价</a-button>
            <a-button v-if="showType == 0" type="primary" @click="cancelOrder">取消订单</a-button>
          </div>
        </div>
      </a-spin>
    </template>
  </MyModal>
</template>

<style scoped lang="less">
.addRemark {
  margin-bottom: 15px;
  margin-right: 15px;
  text-align: right;

  :nth-child(1) {
    margin-right: 10px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.imgBox {
  width: 150px;
  height: 75px;

  img {
    height: 75px;
  }
}

.itemBox {
  display: flex;
  margin-bottom: 10px;
  margin-left: 10px;
}

.title {
  width: 110px;
  text-align: center;
}

.content {
  color: #909193;
  flex: 1;
}
</style>
